﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using com.dz.ht.common;
using com.dz.ht.db;


namespace com.dz.ht.components
{
    #region 消息处理

    /// <summary>
    /// 发送消息的委托
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    public delegate void SendMsgEventHandler(object sender, SendMsgEventArgs e);

    /// <summary>
    /// 发送消息时间参数类
    /// </summary>
    public class SendMsgEventArgs : EventArgs
    {
        private string m_msg;

        /// <summary>
        /// 消息信息
        /// </summary>
        public string Msg
        {
            get { return m_msg; }
            set { m_msg = value; }
        }
    }

    #endregion
    public class NetBookManger
    {
        #region 属性申明
        private string m_site_name = "Site_3";
        public string SiteName
        {
            get { return m_site_name; }
            set { m_site_name = value; }
        }

        private bool m_in_db = false;
        public bool InDB
        {
            get { return m_in_db; }
            set { m_in_db = value; }
        }

        private Consts.Site m_site_id = Consts.Site.shouda8;
        public Consts.Site SiteId
        {
            get { return m_site_id; }
            set { m_site_id = value; }
        
        }

        private string m_url = string.Empty;
        public string Url
        {
            get { return m_url; }
            set { m_url = value; }
        }

        private string m_default_url = string.Empty;
        public string DefaultUrl
        {
            get { return m_default_url; }
            set { m_default_url = value; }
        }

        private bool m_is_last_update = false;

        public bool IsLastUpdate
        {
            get { return m_is_last_update; }
            set { m_is_last_update = value; }
        }

        private string m_format_url = string.Empty;
        public string FormatUrl
        {
            get { return m_format_url; }
            set { m_format_url = value; }
        }

        /// <summary>
        /// 触发发送消息的事件
        /// </summary>
        public event SendMsgEventHandler SendMsg;
        #endregion

        #region 构造函数
        public NetBookManger(string i_site_name)
        {
            switch (i_site_name.ToLower())
            {
                case "site_1":
                    FormatUrl = "http://all.qidian.com/book/bookStore.aspx?ChannelId=-1&SubCategoryId=-1&Tag=all&Size=-1&Action=-1&OrderId=6&P=all&PageIndex={0}&update=-1&Vip=1&Boutique=-1&SignStatus=-1";
                    DefaultUrl = "http://www.qidian.com";
                    SiteId = Consts.Site.qidian;
                    break;
                case "site_2":
                    SiteId = Consts.Site.uutxt;
                    break;
                case "site_3":
                    FormatUrl = "http://www.xiaoshuoyd.com/4/{0}.html";
                    SiteId = Consts.Site.shouda8;
                    break;
                case "site_4":
                    FormatUrl = "http://www.3zcn.com/allvisit-{0}.html";
                    DefaultUrl = "http://www.3zcn.com/";
                    SiteId = Consts.Site.zcn;
                    break;
                case "site_5":
                    FormatUrl = "http://www.caizige.com/czsort/0/{0}.htm";
                    SiteId = Consts.Site.caizige;
                    break;

            }
        }
        #endregion

        #region 消息回送
        /// <summary>
        /// 发送消息到客户端
        /// </summary>
        /// <param name="i_msg"></param>
        private void SendMsg2Client(string i_msg)
        {
            SendMsgEventArgs e = new SendMsgEventArgs();
            e.Msg = i_msg;

            if (SendMsg != null)
            {
                SendMsg(this, e);
            }

        }

        #endregion

        #region 收集书籍
        /// <summary>
        /// 开始从网络收集书籍
        /// </summary>
        public void StartLastUpdateBook()
        {
            while (true)
            {
                for (int index = 1; index < AppConfig.startPageIndex; index++)
                {
                    string t_url = string.Format(FormatUrl, index);
                    StartBookInfo(t_url, -1);
                }
                System.Threading.Thread.Sleep(1000);
            }
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        public void StartListBook()
        {
            while (true)
            {
                for (int index = AppConfig.startPageIndex; index < AppConfig.MaxBookListPageCount; index++)
                {
                    string t_url = string.Format(FormatUrl, index);
                    //StartBookInfo(t_url, -1);
                    StartDefaultBook(t_url);
                }
                System.Threading.Thread.Sleep(1000 * 60);
            }
        }

        /// <summary>
        /// 收集首页书籍
        /// </summary>
        public void StartDefaultBook(string i_url)
        {
           
            IBookObject t_obj = ObjectManger.CreateDbObj(SiteName);
            DataManger t_book_mgr = new DataManger();
            long t_book_id = 0;
            string t_chapter_url = string.Empty;
            try
            {
                Dictionary<string, string> t_url = t_obj.CollectDefaultBookList(i_url);

                if (t_url != null && t_url.Count > 0)
                {
                    foreach (string t_single_url in t_url.Keys)
                    {

                      // CollectSingleBook(t_single_url, -1);
                        t_chapter_url = t_single_url.Replace("info-", "");
                        t_book_id = t_book_mgr.UpdateBookChapterUrl(30, t_url[t_single_url], t_chapter_url);
                        if (t_book_id > 0)
                        {
                            SendMsg2Client(string.Format("小说 {0} 章节地址更新为： {1}", t_url[t_single_url], t_chapter_url));
                        }
                    }
                }
                else
                {
                    SendMsg2Client(string.Format(" 地址 {0} 没有收集到书籍", i_url));
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取首页内容失败" + ex.ToString());
            }

        }

        /// <summary>
        /// 收集某个地址书籍
        /// </summary>
        public void StartBookSignUrl()
        {
             CollectSingleBook(Url, -1);
        }

        /// <summary>
        /// 收集小说信息
        /// </summary>
        /// <param name="i_url"></param>
        public void StartBookInfo(string i_url, int i_type)
        {

            SendMsg2Client(string.Format("开始从{0}收集书籍详细信息.", i_url));

            IBookObject t_obj = ObjectManger.CreateDbObj(SiteName);
          
            //书籍地址url
            Dictionary<string, string> t_book_url_list = null;
            t_book_url_list = t_obj.CollectBookList(i_url);

            if (t_book_url_list != null && t_book_url_list.Count > 0)
            {
                SendMsg2Client(string.Format("收集到{0}本书籍.", t_book_url_list.Count));
               
                foreach (string t_key in t_book_url_list.Keys)
                {
                    CollectSingleBook(t_key,i_type);
                }

            }
        }

        #endregion

        /// <summary>
        /// 搜集一本书的信息
        /// </summary>
        /// <param name="i_url"></param>
        /// <param name="i_type"></param>
        private void CollectSingleBook(string i_url,int i_type)
        {
            DataManger t_book_mgr = new DataManger();
            FileManager t_file_mgr = new FileManager();

            IBookObject t_obj = ObjectManger.CreateDbObj(SiteName);
            long t_book_id = 0;
            long t_chapter_id = 0;
            string t_chapter_content = string.Empty;

            //章节信息
            List<BookChapterInfo> t_chapter_list = null;

            //书详细信息
            BookInfo t_book_info = null;
            string t_last_chapter_name = string.Empty;

            t_book_info = t_obj.CollectBookItem(i_url);

            if (t_book_info == null)
                return;

            t_book_info.AuthorId = i_type;
            t_book_info.CreateTime = DateTime.Now;
            t_book_info.SiteId = (int)m_site_id;

            SendMsg2Client(string.Format("收集到书名：{0}；类型：{1}；作者：{2}；简介：{3}。书籍地址：{4}；章节地址：{5}。是否有封面：{6}", t_book_info.BookName, t_book_info.BookSubCagegoryName, t_book_info.AuthorName, t_book_info.Description, t_book_info.BookUrl, t_book_info.ChapterUrl, t_book_info.IsExistsImage));

                   
            if (InDB)
            {
                if (m_site_id == Consts.Site.zcn)
                    t_book_info.IsExistsImage = false;

                //保存书籍到数据库
                t_book_id = t_book_mgr.InsertBookInfo(t_book_info, out t_last_chapter_name);

                SendMsg2Client(string.Format("入库成功,bookId：{0}.", t_book_id));

                //下载小说封面
                if (m_site_id != Consts.Site.zcn)
                {
                    if (t_book_info.IsExistsImage && t_book_id > 0)
                    {

                        NetSiteCatchManager.DownLoadImage(t_book_info.ImageUrl, t_book_id);

                        SendMsg2Client(string.Format("下载封面：{0}成功", t_book_info.ImageUrl));
                    }
                }

                if (m_site_id == Consts.Site.qidian)
                    return;

            }

            if (InDB)
            {
                if (t_book_id <= 0)
                    return;
            }

            //下载章节
            t_chapter_list = t_obj.CollectChapterList(t_book_info.ChapterUrl);
            string t_chapter_url = string.Empty;

            if (t_chapter_list != null && t_chapter_list.Count > 0)
            {
                SendMsg2Client(string.Format("从地址：{0}，收集到{1}个章节.", t_book_info.ChapterUrl, t_chapter_list.Count));
              
                int t_index = 0;
                if (!string.IsNullOrEmpty(t_last_chapter_name))
                {
                    t_index = t_chapter_list.FindIndex(delegate(BookChapterInfo t_chapter_info)
                    {
                        return t_last_chapter_name.IndexOf(t_chapter_info.ChapterName.Trim()) >= 0;
                    });
                }
                if (t_index < 0)
                    t_index = 0;
                BookChapterInfo t_chapter = null;

                for (int index = t_index; index < t_chapter_list.Count; index++)
                {
                    t_chapter = t_chapter_list[index];

                    t_chapter.SiteId = (int)m_site_id;

                    t_chapter.BookId = t_book_id;

                    t_chapter_url = t_chapter.Comfrom;

                    if (string.IsNullOrEmpty(t_chapter_url))
                        t_chapter_url = string.Format("{0} {1}", t_book_info.BookName, t_chapter.ChapterName);

                    t_chapter_content = t_obj.CollectChapterContent(t_chapter_url);

                    SendMsg2Client(string.Format("从地址：{0}获取章节名称：{1},更新时间：{2},字数：{3}", t_chapter.Comfrom, t_chapter.ChapterName, t_chapter.UpdateTime, t_chapter_content.Length));

                    if (string.IsNullOrEmpty(t_chapter_content))
                        continue;

                    if (InDB)
                    {
                        t_chapter.WordsCount = t_chapter_content.Length;
                        //章节信息保存到数据库
                        t_chapter_id = t_book_mgr.InsertBookChapter(t_chapter,t_last_chapter_name);

                        //章节内容保存到磁盘
                        if (t_chapter_id > 0)
                        {
                           // t_file_mgr.WriteBookContent(t_book_id, t_chapter_id, t_chapter_content);

                        }

                        SendMsg2Client(string.Format("章节保存成功,chapterId:{0}.", t_chapter_id));
                    }

                }
             
            }
        }


        #region 收集需要更新的章节

        public void StartChapter()
        {
            while (true)
            {
                StartCatchChapter();
                System.Threading.Thread.Sleep(12 * 60 * 60 * 1000);//12小时一次
            }
        }

        /// <summary>
        /// 收集章节
        /// </summary>
        public void StartCatchChapter()
        {
            try
            {
                DataManger t_book_mgr = new DataManger();
                DataSet t_ds = t_book_mgr.GetChapter((int)SiteId);
                FileManager t_file_mgr = new FileManager();
                if (t_ds != null && t_ds.Tables[0].Rows.Count > 0)
                {
                    IBookObject t_obj = ObjectManger.CreateDbObj(SiteName);
                    int t_site_id = 0;
                    long t_book_id = 0;
                    long t_chapter_id = 0;
                    string t_chapter_content = string.Empty;
                    string t_chapter_url = string.Empty;
                    for (int index = 0; index < t_ds.Tables[0].Rows.Count; index++)
                    {
                        if (!int.TryParse(t_ds.Tables[0].Rows[index]["siteId"].ToString(), out t_site_id))
                            t_site_id = 0;
                        if (!long.TryParse(t_ds.Tables[0].Rows[index]["bookId"].ToString(), out t_book_id))
                            t_book_id = 0;
                        if (!long.TryParse(t_ds.Tables[0].Rows[index]["chapterId"].ToString(), out t_chapter_id))
                            t_chapter_id = 0;

                        if (t_ds.Tables[0].Rows[index]["comfrom"] != null)
                        {
                            t_chapter_url = t_ds.Tables[0].Rows[index]["comfrom"].ToString();
                            if (!string.IsNullOrEmpty(t_chapter_url))
                            {
                                t_chapter_content = t_obj.CollectChapterContent(t_chapter_url);

                                if (!string.IsNullOrEmpty(t_chapter_content))
                                {
                                   // t_file_mgr.WriteBookContent(t_book_id, t_chapter_id, t_chapter_content);
                                    t_book_mgr.UpdateChapterStatus(t_book_id, t_chapter_id);
                                }

                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                LogHelper.Error("收集需要更新的章节失败" + ex.ToString());
            }
        }

        #endregion
    }
}
